package com.hua.controller;

import ch.qos.logback.core.joran.util.beans.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hua.handler.Result;
import com.hua.mapper.TypeMapper;
import com.hua.mapper.UserMapper;
import com.hua.pojo.*;
import com.hua.service.NovelService;
import com.hua.service.TypeService;
import com.hua.service.UserService;
import com.hua.service.impl.AuthorToexamineServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@RestController
//@Controller
@RequestMapping("/novel")
//@ConditionalOnMissingBean(AuthorToexamineServiceImpl.class)  //当缺失这个AuthorToexamineServiceImpl的时候，条件成立 ->NovelController ->bean
//@Conditional    mybatis plus springdatasource
public class NovelController {

    @Resource
    private NovelService novelService;

    @Resource
    private UserService userService;

    @Autowired
    private TypeMapper typeMapper;

    @Autowired
    private UserMapper userMapper;


    /**
     * 条件分页查询Novel
     * @param pageNum
     * @param pageSize
     * @param search
     * @return
     */
    @GetMapping
    /**
     * @RequestParam用于将请求参数区数据映射到功能处理方法的参数上。defaultValue：默认值，表示如果请求中没有同名参数时的默认值
     *
     */
    @ResponseBody
    public Result<?> NovelFindPage(@RequestParam(defaultValue = "1") Integer pageNum,
                                  @RequestParam(defaultValue = "10") Integer pageSize,
                                  @RequestParam(defaultValue = "") String search){
        //mybatis-plus中的构造器,创建一个构造器
        LambdaQueryWrapper<Novel> wrapper=new LambdaQueryWrapper<Novel>();
        //StuUtil工具类内置了很多方法，isNotBlamk判断字符串是否为空
//        if (StrUtil.isNotBlank(search)){
            //where  "novelName"  like "123" limit 2,5  1
            wrapper.like(StrUtil.isNotBlank(search),Novel::getNovelName,search);
//        }
        //TODO
        Page<NovelVO> resPage = new Page<>(pageNum,pageSize);
        //limit
        Page<Novel> page = novelService.page(new Page<>(pageNum, pageSize), wrapper);
        //DO=>VO
        BeanUtils.copyProperties(page,resPage,"records");
            //TODO 把DO records也给赋值给VO
        List<Novel> records = page.getRecords();
//        records.stream().map()
        List<NovelVO> list = records.stream().map((item)->{
            NovelVO novelVO = new NovelVO();
            BeanUtils.copyProperties(item,novelVO);
            //根据分类id查询分类名称
            Type type = typeMapper.selectById(novelVO.getTypeId());
            novelVO.setTypeName(type.getTypeName());
            User user = userMapper.selectById(novelVO.getUserId());
            novelVO.setNickName(user.getNickName());
            return novelVO;
        }).collect(Collectors.toList());
        resPage.setRecords(list);
        resPage.setTotal(page.getTotal());
        return Result.success(resPage);
    }

    @DeleteMapping
    //Delete为删除，removeByIds为批量删除
    public Result<?> NovelDelete(@RequestBody Set<String> ids){
        novelService.removeByIds(ids);
        return Result.success();
    }

    //新增一条小说的数据
    @PostMapping("addNovel")
    public Result<?> addNovel(@RequestBody Novel novel){
        novelService.save(novel);
        return Result.success();
    }

    //根据用户id查询多行数据
    @PostMapping("/selectNovel/{userId}")
    public Result<?> selectUser(@PathVariable String userId){
        LambdaQueryWrapper<Novel> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Novel::getUserId,userId);
        List<Novel> list = novelService.list(wrapper);
        return Result.success(list);
    }

    //根据用户id查询多行数据,点击量全部相加
    @PostMapping("/selectNovelDjl/{userId}")
    public Result<?> selectNovelDjl(@PathVariable String userId){
        LambdaQueryWrapper<Novel> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Novel::getUserId,userId);
        List<Novel> list = novelService.list(wrapper);
        Integer zongDjl=0;
        for (Novel novel : list) {
            Integer novelHits = novel.getNovelHits();
            zongDjl=novelHits+zongDjl;
        }
        return Result.success(zongDjl);
    }

    //根据分类id查询数据
    @PostMapping("/selectImgName/{typeId}")
    public Result<?> selectImgName(@PathVariable String typeId){
        LambdaQueryWrapper<Novel> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Novel::getTypeId,typeId);
        List<Novel> list = novelService.list(wrapper);
        return Result.success(list);
    }
    //根据小说id查询内容
    @PostMapping("/selectTitle/{novelId}")
    public Result<?> selectNovel(@PathVariable String novelId){
        Novel byId = novelService.getById(novelId);
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUserId,byId.getUserId());
        String nickName = userService.getOne(wrapper).getNickName();
        byId.setUserId(nickName);
        return Result.success(byId);
    }

    ////根据小说id查询内容,(点击量加1)
    @PostMapping("/selectJiaNovelHits/{novelId}")
    public Result<?> selectJiaNovelHits(@PathVariable String novelId){
        Novel byId = novelService.getById(novelId);
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUserId,byId.getUserId());
//        设置点击量加1
        int novelHits = byId.getNovelHits();
        novelHits++;
        byId.setNovelHits(novelHits);
        novelService.updateById(byId);
        String nickName = userService.getOne(wrapper).getNickName();
        byId.setUserId(nickName);
        return Result.success(byId);
    }

    //查询出点击量最高的6位
    @PostMapping("/selectMaxHits")
    public Result<?> selectMaxHits(){
        LambdaQueryWrapper<Novel> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(Novel::getNovelHits);
        List<Novel> list = novelService.list(wrapper );
        return Result.success( list.subList(0,6));

    }

    @PutMapping
    //put为更新
    public Result<?> novelUpdate(@RequestBody Novel novel){
        novelService.updateById(novel);
        return Result.success(novel);
    }
}
